import TLS from 'im-live-sells'
import TIM from 'tim-wx-sdk'
import { getUserSig, like, sendGift, follow, unFollow, getUserInfo, getGiftList, buyGoods, changeRoomStatus } from '../../api/login'
const app = getApp()

Page({
  data: {
    groupInfo: null,
    ownerInfo: null,
    userInfo: null,
    message: [],
    isTimReady: false,
    gifts: [
      {
        id: 1,
        name: '火箭',
        url: '/images/gift-item1.png'
      },
      {
        id: 2,
        name: '鲜花',
        url: '/images/gift-item2.png'
      }
    ],
    showGift: false,
    leftGiftShow: false,
    giftItem: {},
    isFollowed: false,
    isUserCardShow: false,
    isOnLineShow: false,
    memberList: [],
    giftList: [],
    isShowCoupon: false,
    isShowGood: false,
    goodList: []
  },
  async handleBuyGood(event) {
    const data = {
      from_id: this.data.userInfo.userID,
      to_id: this.data.groupInfo.ownerID,
      name: event.detail.name,
      price: event.detail.price,
      id: event.detail.id
    }
    await buyGoods(data)
    this.tls.sendCustomMsgAndEmitEvent('BUY_GOODS', JSON.stringify(event.detail))
    this.tls.buy(JSON.stringify(event.detail)).then(res => {
      this.setData({
        isShowGood: false
      })
    })
  },
  handleShowGood() {
    this.setData({
      isShowGood: true
    })
  },
  handleShowCoupon() {
    this.setData({
      isShowCoupon: true
    })
  },
  handleHideCoupon() {
    this.setData({
      isShowCoupon: false
    })
  },
  handleUseCoupon() {
    this.tls.useCoupon().then(() => {
      this.handleHideCoupon()
    })
  },
  // 在线用户
  async handleShowOnline() {
    this.setData({
      isOnLineShow: true
    })

    const res = await this.tls.getGroupMemberList()
    this.setData({
      memberList: res.data.memberList
    })
  },
  // 礼物榜
  async handleGiftList() {
    const data = {to_id: this.data.groupInfo.ownerID}
    const { giftList } = await getGiftList(data)

    giftList.forEach(item => {
      const current = this.data.gifts.filter(current => current.id === item.gift_id)[0]
      item.name = current.name,
      item.url = current.url
    })

    this.setData({
      giftList
    })
  },
  // 主播卡片
  handleShowUserCard() {
    this.setData({
      isUserCardShow: true
    })
  },
  handleHideUserCard() {
    this.setData({
      isUserCardShow: false
    })
  },
  // 关注
  async handleFollow(event) {
    this.setData({
      isFollowed: event.detail
    })
    if (event.detail) {
      // 关注
      await this.tls.attention()
      const data = {
        from_id: this.data.userInfo.userID,
        to_id: this.data.groupInfo.ownerID
      }
      await follow(data)
      this.setData({
        ownerInfo: {
          ...this.data.ownerInfo,
          fans: this.data.ownerInfo.fans + 1
        }
      })
    } else {
      // 取消关注
      await this.tls.cancelAttention()
      const data = {
        from_id: this.data.userInfo.userID,
        to_id: this.data.groupInfo.ownerID
      }
      await unFollow(data)
      this.setData({
        ownerInfo: {
          ...this.data.ownerInfo,
          fans: this.data.ownerInfo.fans - 1
        }
      })
    }
  },
  // 送礼
  handleShowGift() {
    this.setData({
      showGift: true
    })
  },
  async handleSendGift(event) {
    this.setData({
      showGift: false
    })
    const data = {
      from_id: this.data.userInfo.userID,
      to_id: this.data.groupInfo.ownerID,
      gift_id: event.detail.id,
      gift_name: event.detail.name
    }
    await sendGift(data)
    this.tls.sendGift(JSON.stringify(event.detail))
  },
  handleHideLeftGift() {
    this.setData({
      leftGiftShow: false
    })
  },
  // 发消息
  async handleSend(event) {
    try {
      const res = await this.tls.sendMessage(event.detail)
      const msg = []
      msg.push({
        type: 1,
        name: this.formatNick({
          userID: this.data.userInfo.userID,
          nick: res.nick
        }),
        message: res.message,
        id: `id${Date.now()}`
      })
      this.setData({
        message: [...this.data.message, ...msg]
      })
    } catch (err) {
      if (err.toString().includes('禁言')) {
        wx.showToast({
          title: '您已被禁言',
          icon: 'error'
        })
      }
    }
  },
  async getUserSig() {
    const data = { userID: app.userData.id }
    const res = await getUserSig(data)
    this.initTLS(res)
  },
  async handleBack() { 
    wx.showLoading({
      title: '正在退出...',
      mask: true
    })
    await this.tls.exitRoom()
    wx.navigateBack()
    wx.hideLoading()

    if (app.isLive) {
      app.isLive = false
      const data = { type: 1, im_id: app.liveInfo.im_id}
      await changeRoomStatus(data)
    }
  },
  async handleLike() {
    const data = {'from_id': this.data.userInfo.userID, 'to_id': this.data.groupInfo.groupID}
    const res = await like(data)
    this.tls.like(TLS.EVENT.LIKE)
  },
  initTLS(res) {
    this.tls = new TLS({
      SDKAppID: res.sdkappid,
      roomID: app.liveInfo.im_id,
      userSig: res.userSig,
      userName: app.userData.id,
      TIM: TIM
    })

    // 初始化
    this.tls.on(TLS.EVENT.SDK_READY, async () => {
      let { groupInfo, userInfo} = await this.tls.joinRoom({
        roomID: app.liveInfo.im_id,
        getOwnerInfo: true
      })

      // 进自己的房间
      if (!groupInfo) {
        groupInfo = await this.tls.getRoomInfo()
      }

      if (groupInfo.groupCustomField[0].value) {
        const item = groupInfo.groupCustomField.filter(item => item.key === 'ADD_GOODS')
        this.setData({
          goodList: JSON.parse(item[0].value) || "[]"
        })
      }

      this.setData({
        groupInfo,
        ownerInfo: groupInfo.ownerInfo,
        userInfo,
        isTimReady: true,
      })

      this.notification = groupInfo.notification
      if (this.notification) {
        const msg = []
        msg.push({
          type: 2, // 这是公告
          name: '公告',
          message: this.notification,
          id: `id${Date.now()}`
        })

        this.setData({
          message: [...this.data.message, ...msg]
        })
      }
    })

    // 加入群聊
    this.tls.on(TLS.EVENT.JOIN_GROUP, async (data) => {
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: data.nick,
        message: '进入直播间',
        id: `id${Date.now()}`
      })

      this.setData({
        message: [...this.data.message, ...msg]
      })

      // 获取当前用户是否关注了主播
      this.getUserInfo()
    })

    // 收到消息
    this.tls.on(TLS.EVENT.MESSAGE, async (data) => {
      if (!data.userID) return
      if (!data.message) return
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: data.message,
        id: `id${Date.now()}`
      })

      this.setData({
        message: [...this.data.message, ...msg]
      })
    })

    // 退出直播间
    this.tls.on(TLS.EVENT.EXIT_GROUP, async (data) => {
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: '离开直播间',
        id: `id${Date.now()}`
      })

      this.setData({
        message: [...this.data.message, ...msg]
      })
    })

    // 点赞
    this.tls.on(TLS.EVENT.LIKE, async (data) => {
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: '给主播点赞了',
        id: `id${Date.now()}`
      })

      this.setData({
        message: [...this.data.message, ...msg]
      })
    })

    // 送礼
    this.tls.on(TLS.EVENT.SEND_GIFT, async (data) => {
      const giftInfo = JSON.parse(data.value || data.extension)
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: `给主播送了${giftInfo.name}`,
        id: `id${Date.now()}`
      })

      this.setData({
        message: [...this.data.message, ...msg],
        leftGiftShow: true,
        giftItem: {
          userAvatar: data.avatar,
          userNick: data.nick,
          giftName: giftInfo.name,
          giftUrl: giftInfo.url
        }
      })
    })

    // 关注主播
    this.tls.on(TLS.EVENT.ATTENTION, async (data) => {
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: '关注了主播',
        id: `id${Date.now()}`
      })

      this.setData({
        message: [...this.data.message, ...msg]
      })
    })

    // 取消关注
    this.tls.on(TLS.EVENT.CANCELATTENTION, async (data) => {
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: '取消关注了主播',
        id: `id${Date.now()}`
      })

      this.setData({
        message: [...this.data.message, ...msg]
      })
    })

    // 有人使用了优惠券
    this.tls.on(TLS.EVENT.USE_COUPON, async (data) => {
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: '领取了优惠券',
        id: `id${Date.now()}`
      })
      this.setData({
        message: [...this.data.message, ...msg]
      })
    })

    // 上架了新的商品
    this.tls.on(TLS.EVENT.ADD_GOODS, async (data) => {
      wx.showToast({
        title: '商品有更新'
      })
      this.setData({
        goodList: JSON.parse(data.value || data.extension)
      })
    })

    // 监听有人购买了商品
    this.tls.on(TLS.EVENT.BUY_GOODS, async (data) => {
      const msg = []
      msg.push({
        type: 1, // 这是消息
        name: this.formatNick({
          userID: data.userID,
          nick: data.nick
        }),
        message: `购买了${JSON.parse(data.value || data.extension).name}`,
        id: `id${Date.now()}`
      })
      this.setData({
        message: [...this.data.message, ...msg]
      })
    })
  },
  async getUserInfo() {
    const data = {
      from_id: this.data.userInfo.userID,
      to_id: this.data.groupInfo.ownerID
    }
    const res = await getUserInfo(data)
    this.setData({
      isFollowed: res.isFollowed,
      ownerInfo: {
        ...this.data.ownerInfo,
        fans: res.fans
      }
    })
  },
  formatNick({userID, nick}) {
    if(nick === '') return '管理员'
    if (userID === app.userData.id) {
      return '我'
    }
    return nick
  },
  onLoad() {
    this.getUserSig()
  },
  async onUnload() {
    if (app.isLive) {
      app.isLive = false
      const data = { type: 1, im_id: app.liveInfo.im_id}
      await changeRoomStatus(data)
    }
  }
})